﻿using CSharpToolWPF.Windows;
using Microsoft.Win32;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Automation.Peers;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml;
using Windows.Devices.WiFiDirect;
using Windows.Graphics.Printing.OptionDetails;
using Windows.UI;
using Wpf.Ui.Controls;
using WPFTools;
using Color = System.Windows.Media.Color;
using Path = System.IO.Path;

namespace CSharpToolWPF.Pages
{
    /// <summary>
    /// PageAutoAddDenpendencies.xaml 的交互逻辑
    /// </summary>
    public partial class PageAutoAddDenpendencies : Page
    {
        private static PageAutoAddDenpendencies page;
        public static PageAutoAddDenpendencies Instance { get; set; }

        private WindowInteractivelyFillBlank windowFillBlank {  get; set; }
        //
        private VCXXmlTools vcxXmlTools = null;
        private VCXmlTools vcXmlTools = null;
        //
        App app = (App)Application.Current;
        // 用于中断、等待操作
        private TaskCompletionSource<bool>? taskCompletionSource = null;
        // 
        private Color colorAlert = Color.FromRgb(237, 87, 85);
        private Color colorWarning = Color.FromRgb(237, 173, 85);
        private Color colorOk = Color.FromRgb(167, 237, 85);
        private Color colorNormal = Color.FromRgb(255, 255, 255);
        // 
        // 
        private FontFamily fontSarasa = new FontFamily("Sarasa Term SC");
        private string basePath = "D:/VC/ObjectPRX 2024/sln/";
        public PageAutoAddDenpendencies() {
            InitializeComponent();
            this.KeepAlive = true;
            Instance = this;

            vcxXmlTools = new(rtbLog);
            vcXmlTools = new(rtbLog);

            rtbLog.TextChanged += rtbLog_TextChanged;
            datagridClassLib.ItemsSource = app.ListClassAndLib;
            app.ListClassAndLib.CollectionChanged += ListClassAndLib_CollectionChanged;
            datagridInValidLib.ItemsSource = app.ListInValidLib;

            this.FontFamily = fontSarasa;
            rtbLog.AppendText("\n");
            foreach(var blk in rtbLog.Document.Blocks) {
                blk.FontFamily = fontSarasa;
            }

            this.DataContext = this;
        }

        // 递归遍历所有子控件并设置字体
        private void SetFontForAllControls(DependencyObject parent, FontFamily fontFamily, double fontSize) {
            // 获取父控件下的子控件数量
            int childrenCount = VisualTreeHelper.GetChildrenCount(parent);

            for (int i = 0; i < childrenCount; i++) {
                DependencyObject child = VisualTreeHelper.GetChild(parent, i);

                // 尝试转换为支持字体属性的控件
                if (child is Control control) {
                    control.FontFamily = fontFamily;
                    control.FontSize = fontSize;
                }

                // 如果该控件有子控件，则继续递归
                if (VisualTreeHelper.GetChildrenCount(child) > 0) {
                    SetFontForAllControls(child, fontFamily, fontSize);
                }
            }
        }

        private void DataGrid_LoadingRow(object sender, DataGridRowEventArgs e) {
            string elementName = "";
            if (sender is FrameworkElement frameworkElement) {
                // 获取控件的 x:Name
                elementName = frameworkElement.Name;
            }
            if(elementName== "datagridClassLib") {
                // 给DataGrid添加菜单
                ContextMenu contextMenu = new ContextMenu();
                // 多选删除行
                var deleteMenuItem = new Wpf.Ui.Controls.MenuItem {
                    Header = "删除"
                };
                deleteMenuItem.Click += (s, args) => {
                    // 获取当前行对应的项
                    var selectedItems = datagridClassLib.SelectedItems.Cast<ClassAndLibData>().ToList();
                    foreach (var item in selectedItems) {
                        app.ListClassAndLib.Remove(item);
                        datagridClassLib.Items.Refresh();
                    }
                };
                // 多勾选有错误列
                var MultiCheckInValid = new Wpf.Ui.Controls.MenuItem {
                    Header = "多勾选有错误列"
                };
                MultiCheckInValid.Click += (s, args) => {
                    // 获取当前行对应的项
                    var selectedItems = datagridClassLib.SelectedItems.Cast<ClassAndLibData>().ToList();
                    foreach (var item in selectedItems) {
                        item.IsInValidNow = item.IsInValidNow ? false : true;
                        datagridClassLib.Items.Refresh();
                    }
                };
                // 删除所选的库名LibName
                var RemoveSelectedLibName = new Wpf.Ui.Controls.MenuItem {
                    Header = "删除所选的库名LibName"
                };
                RemoveSelectedLibName.Click += (s, args) => {
                    // 获取当前行对应的项
                    var selectedItems = datagridClassLib.SelectedItems.Cast<ClassAndLibData>().ToList();
                    foreach (var item in selectedItems) {
                        item.LibName = "";
                        datagridClassLib.Items.Refresh();
                    }
                };
                // 将删除菜单项添加到上下文菜单
                contextMenu.Items.Add(deleteMenuItem);
                contextMenu.Items.Add(MultiCheckInValid);
                contextMenu.Items.Add(RemoveSelectedLibName);

                // 将上下文菜单赋值给当前行
                e.Row.ContextMenu = contextMenu;
            }
            else if (elementName == "datagridInValidLib") {
                // 
                ContextMenu contextMenu = new ContextMenu();
                // 
                var deleteMenuItem = new Wpf.Ui.Controls.MenuItem {
                    Header = "删除"
                };
                // 绑定删除菜单项的点击事件
                deleteMenuItem.Click += (s, args) => {
                    // 获取当前行对应的项
                    var selectedItems = datagridInValidLib.SelectedItems.Cast<InValidLibData>().ToList();
                    foreach (var item in selectedItems) {
                        app.ListInValidLib.Remove(item);
                        datagridInValidLib.Items.Refresh();
                    }
                };
                // 将删除菜单项添加到上下文菜单
                contextMenu.Items.Add(deleteMenuItem);
                // 将上下文菜单赋值给当前行
                e.Row.ContextMenu = contextMenu;
            }
        }
        private void CheckDuplicate() {
            // 使用HashSet来跟踪已经遇到的ClassName
            HashSet<string> encounteredClassNames = new HashSet<string>();

            // 使用ToList()来安全地进行删除操作，避免修改正在遍历的集合
            var uniqueItems = app.ListClassAndLib.Where(item => encounteredClassNames.Add(item.ClassName)).ToList();

            // 清空原集合并重新添加唯一项
            app.ListClassAndLib.Clear();
            foreach (var item in uniqueItems) {
                app.ListClassAndLib.Add(item);
            }

            // 将存在于 listInValidLib 里的库的"不可用"勾选
            // 获取listInValidLib中的所有LibName
            var invalidLibNames = app.ListInValidLib.Select(lib => lib.LibName).ToList();

            // 更新app.ListClassAndLib中IsInValidNow的状态
            foreach (var classAndLib in app.ListClassAndLib) {
                if (invalidLibNames.Contains(classAndLib.LibName)) {
                    classAndLib.IsInValidNow = true;
                }
                else {
                    classAndLib.IsInValidNow = false;
                }
            }
        }
        private bool DataValidate() {
            bool isValid = app.ListClassAndLib.Where(item => string.IsNullOrEmpty(item.ClassName) || string.IsNullOrEmpty(item.LibName)).Count() == 0;
            if (!isValid) {
                Logger.WriteLog($"数据存在空项，请检查后再点击继续！\n", rtbLog, colorAlert);
            }
            return isValid;
        }
        private async void btnStart_Click(object sender, RoutedEventArgs e) {
            btnStart.IsEnabled = false;
            List<string> filePathList = new List<string>();
            foreach (Block blk in rtbFileList.Document.Blocks) {
                var para = blk as Paragraph;
                if (para == null) {
                    continue;
                }
                var run = para.Inlines.ElementAt(0) as Run;
                if (run == null) {
                    continue;
                }
                filePathList.Add(run.Text);
            }
            // Key为项目名，带编号，Value为log文件路径
            var listLogFile = new List<KeyValuePair<string, string>>();
            foreach (string path in filePathList) {
                if (!Directory.Exists(path)) {
                    continue;
                }
                string projectName = Path.GetFileName(path);
                string logFilePath = "";
                if (checkBoxIsNewProject.IsChecked == true) {
                    logFilePath = $"{path}/Debug/{projectName}.log";
                }
                else {
                    logFilePath = $"{path}/Debug/BuildLog.htm";
                }
                if (!File.Exists(logFilePath)) {
                    Logger.WriteLog($"没有找到项目 {projectName} 的生成 log！请先生成！\n", rtbLog, colorWarning, false);
                    continue;
                }
                listLogFile.Add(new KeyValuePair<string, string>(projectName, logFilePath));
            }
            if(listLogFile.Count == 0) {
                Logger.WriteLog($"没有能够修改的项目！\n", rtbLog, colorWarning, fontSize: 20);
                btnStart.IsEnabled = true;
                return;
            }
            // 保存每个项目需要添加的依赖的类名
            var dictClassesThatProjectNeeded = new Dictionary<string,List<string>>();

            // 避免重复添加同一个库
            var listAddedLib = new List<string>();
            // 
            foreach (var arg in listLogFile) {
                string content = File.ReadAllText(arg.Value);
                var matchesLibMissing = Regex.Matches(content, @"无法打开文件.+\\(\w+.lib)");
                // 没有链接错误关键词
                if (!(content.LastIndexOf("LNK2019") >= 0 || content.LastIndexOf("LNK2001") >= 0)) {
                    if (content.IndexOf("未声明的标识符") >= 0) {
                        Logger.WriteLog($"项目 {arg.Key} 编译存在资源相关编译错误！\n", rtbLog, colorWarning, false);
                        var matches = Regex.Matches(content, @"[""“”](ID\w+)[""“”].+未声明的标识符");
                        var listMissingIDs = matches.Select(item => item.Groups[1].Value).ToList();
                        listMissingIDs.Sort();
                        Logger.WriteLog($"以下是缺少的资源，一般只需要复制IDD开头的过来即可，其他会被VS自动添加：\n", rtbLog, colorWarning, false);
                        Logger.WriteLog(string.Join(",\n", listMissingIDs) + "\n\n", rtbLog, colorNormal, false);
                        continue;
                    }
                    // 匹配到缺少lib
                    else if (matchesLibMissing.Count > 0) {
                        Logger.WriteLog($"项目 {arg.Key} 找不到以下lib文件:\n", rtbLog, colorAlert, false);
                        foreach(Match match in matchesLibMissing) {
                            Logger.WriteLog($"{match.Groups[1].Value}\n", rtbLog, colorWarning, false);
                        }
                        Logger.WriteLog($"\n", rtbLog, colorWarning, false);
                        continue;
                    }
                    // 匹配到循环依赖
                    else if (content.LastIndexOf("循环依赖") >= 0) {
                        Logger.WriteLog($"项目 {arg.Key} 存在循环依赖！\n", rtbLog, colorAlert, false);
                        continue;
                    }
                    // 同时没有 error 关键词表示成功
                    else if (content.IndexOf("error") >= 0) {
                        Logger.WriteLog($"项目 {arg.Key} 编译存在编译错误！\n", rtbLog, colorAlert, false);
                        continue;
                    }
                    else {
                        Logger.WriteLog($"项目 {arg.Key} 编译已成功！\n", rtbLog, colorOk, false);
                        continue;
                    }
                }
                // 读取log内容，匹配每行第一个双冒号前面的类名\
                string[] contentLines = content.Split("\r\n");
                // 预处理，删除"该符号在函数"后面的内容因为那部分内容指示的是符号被调用的位置，而不是需要调用的符号
                contentLines = contentLines.Select(item => {
                    int index = item.LastIndexOf("该符号在函数");
                    if (index < 0) {
                        return item;
                    }
                    item = item.Substring(0, index);
                    return item;
                }).ToArray();
                // Groups[0]
                string pattern = @"(?:__thiscall|__cdecl|__stdcall) (?<FullName>([A-Za-z0-9_]+)(?:::([~A-Za-z0-9_]+))*)";
                var classesThatNeeded = new List<string>();
                // 
                foreach (string line in contentLines) {
                    // 搜索一些特例
                    if (line.IndexOf("__declspec(dllimport) class AcGeTol g_Tol") >= 0 ) {
                        classesThatNeeded.Add("g_Tol");
                    }
                    // 
                    var match = Regex.Match(line, pattern);
                    string fullname = match.Groups["FullName"].Value;
                    if (string.IsNullOrEmpty(fullname)) {
                        continue;
                    }
                    string[] splitNames = fullname.Split("::");

                    string res = "";
                    if (splitNames.Length == 0) {
                        continue;
                    }
                    else if (splitNames.Length == 1) {
                        res = splitNames[0];
                    }
                    else if (splitNames.Length >= 2) {
                        res = splitNames[splitNames.Length - 2];
                    }

                    classesThatNeeded.Add(res);
                }
                classesThatNeeded = classesThatNeeded.Distinct().ToList();
                // 保存到列表显示出来
                foreach (string name in classesThatNeeded) {
                    app.ListClassAndLib.Add(new ClassAndLibData(name, "", false));
                }
                // 保存到字典用于之后处理步骤
                dictClassesThatProjectNeeded.Add(arg.Key, classesThatNeeded);
                //
                Logger.WriteLog($"读取了项目 {arg.Key} 依赖的类:\n", rtbLog, colorOk, false);
                Logger.WriteLog($"{{", rtbLog, colorNormal, false);
                classesThatNeeded.ForEach(item => {
                    Logger.WriteLog($"{item}", rtbLog, Colors.YellowGreen, false);
                    Logger.WriteLog($",", rtbLog, colorNormal, false);
                });
                Logger.WriteLog($"}}\n", rtbLog, colorNormal, false);
                Logger.WriteLog($"已显示在表中，请编辑对应的项目。\n\n", rtbLog, colorOk, false);
            }
            //
            Logger.WriteLog($"完成后点击继续\n\n", rtbLog, colorWarning, fontSize: 20);
            bool isDataValid = false;
            while (!isDataValid) {
                // 去重
                CheckDuplicate();
                // 等待点击继续
                btnContinue.Visibility = Visibility.Visible;
                taskCompletionSource = new();
                await taskCompletionSource.Task;
                // 如果点击了取消，则直接退出
                if (!taskCompletionSource.Task.Result) {
                    taskCompletionSource = new();
                    return;
                }
                taskCompletionSource = new();
                isDataValid = DataValidate();
            }
            // 继续下一步操作
            foreach (var dict in dictClassesThatProjectNeeded) {
                // 继续操作，先检查是否有ClassName重复的
                CheckDuplicate();
                // 遍历 DataGrid 元素，给当前处理到的项目添加依赖项
                string projectPath = "";
                if(checkBoxIsNewProject.IsChecked == true) {
                    projectPath = $"{this.basePath}{dict.Key}/{dict.Key}.vcxproj";
                }
                else {
                    projectPath = $"{this.basePath}{dict.Key}/{dict.Key}.vcproj";
                }
                app.ListClassAndLib.Where(item => string.IsNullOrEmpty(item.ClassName) && string.IsNullOrEmpty(item.LibName)).ToList();
                Logger.WriteLog($"开始处理项目 \"{dict.Key} :\n", rtbLog, colorOk, true, 20);
                foreach (string name in dict.Value) {
                    // 从表格取出对应 name 的行
                    var item = app.ListClassAndLib.FirstOrDefault(item=>item.ClassName==name);
                    if (item == null) {
                        continue;
                    }
                    if (item.IsInValidNow) {
                        Logger.WriteLog($"项目 \"{dict.Key}\" 需要的依赖项 \"{item.LibName}\" 不可用，不添加。\n", rtbLog, colorAlert, false, 14);
                        continue;
                    }
                    // 检查是否重复添加
                    if (listAddedLib.Contains(item.LibName)) {
                        Logger.WriteLog($"项目 \"{dict.Key}\" 已有依赖项 \"{item.LibName}\"，不再重复添加。\n", rtbLog, colorAlert, false, 14);
                        continue;
                    }
                    // 检查是否是自身
                    if (item.LibName == dict.Key) {
                        //Logger.WriteLog($"项目 \"{dict.Key}\" 依赖自身！跳过。\n", rtbLog, colorAlert, false, 14);
                        continue;
                    }
                    // 检测是否已添加
                    string content = File.ReadAllText(projectPath);
                    int index = content.IndexOf($"{item.LibName}.vcxproj");
                    if (index >= 0) {
                        Logger.WriteLog($"项目 \"{dict.Key}\" 已经添加了依赖项 \"{item.LibName}\" ！跳过。\n", rtbLog, colorAlert, false, 14);
                        continue;
                    }
                    // 添加到项目中，分新旧项目处理
                    // 给新项目添加
                    if (checkBoxIsNewProject.IsChecked == true) {
                        if (checkBoxIsStrictInputLib.IsChecked == true || item.IsExternalLib) {
                            var inputLibNode = vcxXmlTools.GetOriginalInputLibsNode(projectPath);
                            if (inputLibNode == null) {
                                Logger.WriteLog($"对项目 \"{dict.Key}\" 添加输入库 \"{item.LibName}\" 时没有找到输入库节点！\n", rtbLog, colorAlert, false, 14);
                                continue;
                            }
                            if (string.IsNullOrEmpty(inputLibNode.InnerText)) {
                                inputLibNode.InnerText += item.LibName;
                            }
                            else if (Regex.Match(inputLibNode.InnerText, @$"\b{item.LibName}\b").Success) {
                                Logger.WriteLog($"项目 \"{dict.Key}\" 已有输入库 \"{item.LibName}\"，不再重复添加！\n", rtbLog, colorWarning, false, 14);
                                continue;
                            }
                            else {
                                inputLibNode.InnerText += ";" + item.LibName;
                            }
                            if (!item.IsExternalLib && checkBoxIsStrictInputLib.IsChecked == true) {
                                inputLibNode.InnerText += "10d.lib";
                            }
                            var xmlDoc = inputLibNode.OwnerDocument;
                            xmlDoc.Save(projectPath);
                        }
                        else if (!vcxXmlTools.AddDependencies(projectPath, item.LibName)) {
                            Logger.WriteLog($"对项目 \"{dict.Key}\" 添加依赖项 \"{item.LibName}\" 的操作失败！\n", rtbLog, colorAlert, false, 14);
                            continue;
                        }
                        // 
                        listAddedLib.Add(item.ClassName);
                        Logger.WriteLog($"已对项目 \"{dict.Key}\" 添加依赖项 \"{item.LibName}\"\n", rtbLog, colorOk, false, 14);
                    }
                    // 给旧项目添加 暂时跟上面写一样的了，之后再把Tools改成接口吧
                    // TODO: 把 VCXXmlTools 和 VCXmlTools 改成接口，然后优化此处代码
                    else {
                        var xmlDoc = new XmlDocument();
                        xmlDoc.Load(projectPath);

                        string inputLibFullName = item.LibName;
                        if (!item.IsExternalLib) {
                            if (checkBoxIsDebug.IsChecked == true) {
                                inputLibFullName += "10d.lib";
                            }
                            else {
                                inputLibFullName += "10.lib";
                            }
                        }

                        if (!vcXmlTools.AddInputLib(xmlDoc, inputLibFullName, isDebug: true)) {
                            Logger.WriteLog($"对项目 \"{dict.Key}\" 添加输入库 \"{item.LibName}\" 的操作失败！\n", rtbLog, colorAlert, false, 14);
                            continue;
                        }

                        vcXmlTools.SaveInGB2312(xmlDoc, projectPath);
                        // 
                        listAddedLib.Add(item.ClassName);
                        Logger.WriteLog($"已对项目 \"{dict.Key}\" 添加输入库 \"{item.LibName}\"\n", rtbLog, colorOk, false, 14);
                    }
                }
            }
        }
        private void rtbFileList_DragEnter(object sender, DragEventArgs e) {
            if (e.Data.GetDataPresent(DataFormats.FileDrop)) {
                e.Effects = DragDropEffects.Copy;
            }
            else
                e.Effects = DragDropEffects.None;
            e.Handled = true;
        }

        private void btnPickSln_Click(object sender, RoutedEventArgs e) {
            var fileDialog = new OpenFileDialog();
            //fileDialog.FileName = "Document"; // Default file name
            //fileDialog.DefaultExt = ".sln"; // Default file extension
            fileDialog.Filter = "文件夹|*.this.directory"; // Filter files by extension

            // Show open file dialog box
            bool? result = fileDialog.ShowDialog();
            string file = "";
            // Process open file dialog box results
            if (result == true) {
                // Open document
                file = fileDialog.FileName;
            }
            tbSlnPath.Text = file;
        }

        private void tbSlnPath_Drop(object sender, DragEventArgs e) {
            if (e.Data.GetDataPresent(DataFormats.FileDrop)) {
                // 获取文件路径数组
                string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);

                // 清空 RichTextBox 内容
                rtbFileList.Document.Blocks.Clear();

                // 遍历文件路径并显示在 RichTextBox 中
                foreach (var file in files) {
                    Paragraph paragraph = new Paragraph(new Run(file));
                    rtbFileList.Document.Blocks.Add(paragraph);
                }
            }
        }

        private void btnContinue_Loaded(object sender, RoutedEventArgs e) {
            if (taskCompletionSource == null || taskCompletionSource.Task.IsCompleted) {
                btnContinue.Visibility = Visibility.Hidden;
            }
        }

        // 点击运行后出现的继续按钮
        private void btnContinue_Click(object sender, RoutedEventArgs e) {
            taskCompletionSource.SetResult(true);
            btnContinue.Visibility = Visibility.Hidden;
            btnStart.IsEnabled = true;
        }
        // 继续按钮右键菜单里的取消
        private void MenuCancelClick(object sender, RoutedEventArgs e) {
            taskCompletionSource.SetResult(false);
            btnContinue.Visibility = Visibility.Hidden;
            btnStart.IsEnabled = true;
        }

        private void btnNewLine_Click(object sender, RoutedEventArgs e) {
            app.ListClassAndLib.Add(new ClassAndLibData("", "", false));
        }

        private void btnSaveList_Click(object sender, RoutedEventArgs e) {
            app.SaveList();
        }

        private void btnTest_Click(object sender, RoutedEventArgs e) {
            var window = Window.GetWindow(this) as MainWindow;
            if (window == null) {
                return;
            }
            //this.Height = window.MainFrame.ActualHeight;
        }

        private void rtbLog_TextChanged(object sender, TextChangedEventArgs e) {
            var window = Window.GetWindow(this) as MainWindow;
            if (window == null) {
                return;
            }
            //rtbLog.Height = (window.MainFrame.ActualHeight - 125) / 2 - 2;
            rtbLog.ScrollToEnd();
        }

        private void ListClassAndLib_CollectionChanged(object? sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) {
            var window = Window.GetWindow(this) as MainWindow;
            if (window == null) {
                return;
            }
            //datagridClassLib.Height = (window.MainFrame.ActualHeight - 125) / 2 - 2;
        }

        private void Page_Loaded(object sender, RoutedEventArgs e) {
            //rtbLog_TextChanged(null, null);
            //app.ListClassAndLib_CollectionChanged(null, null);
            //rtbFileList_TextChanged(null, null);
            if (taskCompletionSource != null && (taskCompletionSource.Task.IsCanceled || taskCompletionSource.Task.IsCompleted)) {
                btnContinue.Visibility = Visibility.Visible;
            }
        }

        private void Page_SizeChanged_1(object sender, SizeChangedEventArgs e) {
            //if (rtbLog != null && datagridClassLib != null) {
            //    Page_Loaded(null, null);
            //}
        }

        private void rtbFileList_TextChanged(object sender, TextChangedEventArgs e) {
            var window = Window.GetWindow(this) as MainWindow;
            if (window == null) {
                return;
            }
            //rtbFileList.Height = (window.MainFrame.ActualHeight - 125) - 2;
        }

        private void btnClearLog_Click(object sender, RoutedEventArgs e) {
            rtbLog.Document.Blocks.Clear();
            rtbLog.AppendText("等待执行...\n\n");
        }

        private void btnInValidNewLine_Click(object sender, RoutedEventArgs e) {
            app.ListInValidLib.Add(new InValidLibData(""));
        }

        private void btnInteractivelyFillBlank_Click(object sender, RoutedEventArgs e) {
            windowFillBlank = new WindowInteractivelyFillBlank(app.ListClassAndLib);
            windowFillBlank.Owner = Window.GetWindow(this) as MainWindow;
            windowFillBlank.ShowDialog();
            datagridClassLib.Items.Refresh();
        }

        private void TextBox_KeyDown(object sender, KeyEventArgs e) {
            if (e.Key == Key.Enter) {
                var match = app.ListClassAndLib.FirstOrDefault(item=>(item.ClassName==tbSearch.Text)||(item.LibName==tbSearch.Text));
                if (match == null) {
                    return;
                }
                datagridClassLib.ScrollIntoView(match);
                datagridClassLib.SelectedItem = match;
            }
        }

        private void checkBoxIsNewSln_Clicked(object sender, RoutedEventArgs e) {
            var checkBox = sender as CheckBox;
            if (checkBox == null) {
                return;
            }
            if (checkBoxIsStrictInputLib == null) {
                return;
            }

            if (checkBox.IsChecked == false) {
                checkBoxIsStrictInputLib.Visibility = Visibility.Collapsed;
            }
            else {
                checkBoxIsStrictInputLib.Visibility = Visibility.Visible;
            }
        }
    }
}
